package personal.zq.practice.common.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import java.util.LinkedList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

/**
 * excel分批读取
 *
 * @author 尚气(zhao tian hao)
 * @version 1.0
 * @date 2020/2/26 22:19
 */
@Slf4j
public abstract class ExcelDataListener<T> extends AnalysisEventListener<T> {

    /**
     * 每隔3000条存储数据库，然后清理list
     */
    private static final int BATCH_COUNT = 3000;
    protected List<T> list = new LinkedList<>();

    @Override
    public void invoke(T data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 继承此方法处理数据
     */
    protected void saveData() {
        log.info("{}条数据，自定义方法进行处理！", list.size());
    }

}

